package com.dzk.cp.c11x5.dao.impl.hbn;

import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.dzk.cp.c11x5.dao.R5Dao;
import com.dzk.cp.c11x5.pojo.R5;

public abstract class R5DaoHbnImpl<T extends R5> extends HibernateDaoSupport implements R5Dao<T> {

	@Override
	public void save(T r5) {
		super.getHibernateTemplate().save(r5);
	}
	
	@Override
	public void batchSave(List<T> r5s) {
		super.getHibernateTemplate().saveOrUpdateAll(r5s);
	}
	
	@Override
	public int getCount() {
		String sql = "select count(1) from " + getTableName();
		return ((Number) super.getSession().createSQLQuery(sql).uniqueResult()).intValue();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public T getLastR5() {
		String hql = "from " + getEntityClass().getSimpleName() + " r where r.id = " + this.getCount();
		return (T) super.getSession().createQuery(hql).uniqueResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public T getR5ByQs(String issue) {
		String hql = "from " + getEntityClass().getSimpleName() + " r where r.qs = ?";
		return (T) super.getSession().createQuery(hql).setString(0, issue).uniqueResult();
	}
	
	@Override
	public int getYl(String issue, String code) {
		T r5 = this.getR5ByQs(issue);
		if (r5 != null) {
			String sql = "select r.id from " + getTableName() + " r where r.id < ? and r.ns = ? order by r.id desc limit 1";
			Object obj = super.getSession().createSQLQuery(sql).setInteger(0, r5.getId()).setString(1, code).uniqueResult();
			if (obj != null) {
				return r5.getId() - ((Number) obj).intValue() - 1;
			}
		}
		return -1;
	}

	@Override
	public int getCurrentYl(String code) {
		T r5 = this.getLastR5();
		if (r5 != null) {
			String sql = "select r.id from " + getTableName() + " r where r.id < ? and r.ns = ? order by r.id desc limit 1";
			Object obj = super.getSession().createSQLQuery(sql).setInteger(0, r5.getId() + 1).setString(1, code).uniqueResult();
			if (obj != null) {
				return r5.getId() - ((Number) obj).intValue();
			}
		}
		return -1;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<T> query(String fromDate, String toDate) {
		String hql = "from " + getEntityClass().getSimpleName() + " r where r.qs >= ? and r.qs <= ?";
		fromDate = fromDate.replaceAll("-", "");
		toDate = toDate.replaceAll("-", "");
		return super.getSession().createQuery(hql).setString(0, fromDate + "01").setString(1, toDate + "99").list();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<T> queryLatest(int num) {
		String hql = "from " + getEntityClass().getSimpleName() + " r where r.id > ?";
		return super.getSession().createQuery(hql).setInteger(0, getCount() - num).list();
	}
	
	protected abstract Class<T> getEntityClass();
	
	protected abstract String getTableName();

}
